package net.freebytes.ssmp.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * 环境配置
 *
 * @author 千里明月
 * @date 2021/7/20
 **/
@Configuration
public class EnvironmentConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(EnvironmentConfiguration.class);
    @Value("${web.staticSource}")
    private String uploadPath;
    @Value("${web.projectPath}")
    private String projectPath;
    @Value("${web.front:./work/front}")
    private String webFrontPath;

    public static final String EXECUTOR_NAME = "scheduledExecutorService";


    @Bean
    @ConditionalOnMissingBean(EnvironmentProperties.class)
    public EnvironmentProperties environmentProperties() {
        if (StringUtils.isBlank(projectPath)) {
            logger.warn("未创建外部静态资源目录，不具备上传功能");
            return null;
        }
        File file = new File(uploadPath);
        File file2 = new File(webFrontPath);
        try {
            if (!file.exists()) {
                file.mkdirs();
                file.createNewFile();
            }
            if (!file2.exists()) {
                file2.mkdirs();
            }
        } catch (IOException e) {
            logger.error("项目环境文件夹无法创建", e);
            return null;
        }
        EnvironmentProperties properties = new EnvironmentProperties();
        properties.setUploadPath(uploadPath);
        properties.setWebFrontPath(webFrontPath);
        return properties;
    }

    /**
     * 执行周期性或定时任务
     */
    @Bean(name = EXECUTOR_NAME)
    protected ScheduledExecutorService scheduledExecutorService() {
        return new ScheduledThreadPoolExecutor(50,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build());
    }


}
